#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <signal.h>
#include <strings.h>

using namespace std;

void signal_handler(int sig);

const char *host_ip = "127.0.0.1";
const int   host_port = 7000;
bool b_is_running = true;

int main()
{
    int server_socket = socket(AF_INET, SOCK_STREAM, 0);
    if (server_socket == -1) {
        cerr << "create socket error" << endl;
        return 1;
    }

    struct sockaddr_in server_addr;
    bzero(&server_addr, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = inet_addr(host_ip);
    server_addr.sin_port = htons(7000);

    if (bind(server_socket, (const struct sockaddr*)&server_addr, 
                sizeof(server_addr)) == -1) {
        cerr << "bind error" << endl;
        close(server_socket);
        return 1;
    }
    cout << "binding at " << host_port << endl;

    listen(server_socket, 10);

    cout << "--Start--" << endl;

    signal(SIGKILL, signal_handler);

    struct sockaddr client_addr;
    socklen_t client_addr_len;

    int client_socket = accept(server_socket, &client_addr, &client_addr_len);
    if (client_socket == -1) {
        cerr << "accept error." << endl;
    } else {
        cout << "accept connect." << endl;
    }

    const int buffer_size = 1024;
    char buffer[buffer_size] = {0};

    while (b_is_running) {
        bzero(buffer, buffer_size);
        int rsize = recv(client_socket, buffer, buffer_size, 0);
        cout << "recv: " << buffer;
        send(client_socket, "Got it.\n", 8, 0);
    }

    close(client_socket);
    close(server_socket);
    cout << "--End--" << endl;
    return 0;
}

void signal_handler(int sig)
{
    b_is_running = false;    
    cout << "Ctrl+C" << endl;
}
